package edu.chinasoft.handler;

import org.springframework.core.convert.converter.Converter;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/*
*自定义类型转换器
* */
public class StringToDate implements Converter<String,Date> {
    @Override
    public Date convert(String source) {

        Date result=null;
        String pattern="";
        if(source.matches("\\d{4}-\\d{2}-\\d{2}")){
            pattern="yyyy-MM-dd";
        }else if(source.matches("\\d{4}:\\d{2}:\\d{2}")){
            pattern="yyyy:MM:dd";
        }else if(source.matches("\\d{4}/\\d{2}/\\d{2}")){
            pattern="yyyy/MM/dd";
        }

        //时间转换格式类
        SimpleDateFormat dateFormat = new SimpleDateFormat(pattern);
        try {
            //把字符串安装正则表达式转换成时间类型
            result= dateFormat.parse(source);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return result;
    }
}
